const Database = require('better-sqlite3');
const db = new Database('app.db');

class Task {
    static addTask(user_id, text) {
        const stmt = db.prepare('INSERT INTO tasks (user_id, text) VALUES (?, ?)');
        stmt.run(user_id, text);
    }

    static getTasks(user_id) {
        return db.prepare('SELECT * FROM tasks WHERE user_id = ?').all(user_id);
    }

    static deleteTask(task_id) {
        console.log(`Deleting task with ID: ${task_id}`);
        const stmt = db.prepare('DELETE FROM tasks WHERE id = ?');
        const result = stmt.run(task_id);
        
        console.log(`Deleted rows: ${result.changes}`); // 这里检查已经被删除的行
        if (result.changes === 0) {
            console.log(`No task found with ID: ${task_id}`);
        }
    }

    static updateTask(task_id, text) {
        const stmt = db.prepare('UPDATE tasks SET text = ? WHERE id = ?');
        stmt.run(text, task_id);
    }

    static deleteAllTasks(user_id) {
        const stmt = db.prepare('DELETE FROM tasks WHERE user_id = ?');
        stmt.run(user_id);
    }
}

module.exports = { Task, db };